﻿using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
public class FX_UVscroll_delay : MonoBehaviour
{
	public int targetMaterialSlot = 0;

	public AnimationCurve AxisX = AnimationCurve.Linear( 0, 0, 1, 0 );
	public AnimationCurve AxisY = AnimationCurve.Linear( 0, 0, 1, 0 );
	public float MaxTime = 1f;
	public float DelayTime = 0f;

	private float _cur_time_x;
	private float _cur_time_y;

	private float value_x;
	private float value_y;

	void Awake()
	{
		CheckVersion();
	}

	void Start()
	{
		StartCoroutine( UpdateX() );
		StartCoroutine( UpdateY() );
	}

	IEnumerator UpdateX()
	{
		var wait_time = Time.deltaTime;

		var y = _cur_time_x / MaxTime;

		value_x = AxisX.Evaluate(y);

		if( _cur_time_x >= MaxTime )
		{
			_cur_time_x -= MaxTime;
			wait_time = DelayTime;
		}

		if( Application.isPlaying )
			renderer.materials[targetMaterialSlot].SetTextureOffset( "_MainTex", new Vector2( value_x, value_y ) );
		yield return new WaitForSeconds( wait_time );

		_cur_time_x += Time.deltaTime;
		StartCoroutine( UpdateX() );
	}

	IEnumerator UpdateY()
	{
		var wait_time = Time.deltaTime;

		var y = _cur_time_y / MaxTime;

		value_y = AxisY.Evaluate( y );

		if( _cur_time_y >= MaxTime )
		{
			_cur_time_y -= MaxTime;
			wait_time = DelayTime;
		}

		if( Application.isPlaying )
			renderer.materials[targetMaterialSlot].SetTextureOffset( "_MainTex", new Vector2( value_x, value_y ) );
		yield return new WaitForSeconds( wait_time );

		_cur_time_y += Time.deltaTime;
		StartCoroutine( UpdateY() );
	}

	// old_version
	#region Old_Version
	public float speedY = float.MaxValue * .5f;
	public float speedX = float.MaxValue * .5f;
	public float delay_time = float.MaxValue * .5f;
	public float delay_gap = float.MaxValue * .5f;

	public void CheckVersion()
	{
		const float default_value = float.MaxValue * .5f;

		if( !speedX.Equals( default_value ) )
		{
			var target = speedX > 0 ? 1 : speedX < 0 ? -1 : 0;
			MaxTime = 1 / ( Mathf.Abs( speedX ) > 0f ? Mathf.Abs( speedX ) : 1f );
			AxisX = AnimationCurve.Linear( 0, 0, 1, target );
			speedX = default_value;
		}

		if( !speedY.Equals( default_value ) )
		{
			var target = speedY > 0 ? 1 : speedY < 0 ? -1 : 0;
			MaxTime = 1 / ( Mathf.Abs( speedY ) > 0f ? Mathf.Abs( speedY ) : 1f );
			AxisY = AnimationCurve.Linear( 0, 0, 1, target );
			speedY = default_value;
		}

		if( !delay_time.Equals( default_value  ) )
		{
			DelayTime = delay_time;
			delay_time = default_value;
		}
	}
	#endregion
}
